package com.example.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOutputParameters;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * TODO
 *
 * @author ding
 * @since 2024/6/3
 */
@Slf4j
public class Doc2PdfUtil {

    public static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("license.xml")) {

            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            log.error("获取licence错误", e);
        }
        return result;
    }

    public static void doc2pdf(byte[] bytes, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        FileOutputStream os = null;
        try {

            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            Document document = new Document(inputStream);
//            if (SystemUtils.IS_OS_LINUX) {
//                //设置汉字字体，否则转换后的文档汉字会乱码。
//                FontSettings settings = new FontSettings();
//                settings.setFontsFolder("C:\\Windows\\Fonts", false);
//                document.setFontSettings(settings);
//            }
            SaveOutputParameters save = document.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            log.error("pdf转换错误", e);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("pdf转换错误", e);
                }
            }
        }
    }


}
